package de.grosjohann.android.feuerwehr.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.notification.Notify;
import de.grosjohann.android.feuerwehr.util.FileUtil;
import de.grosjohann.android.feuerwehr.webservice.WeatherWsFacade;

public class WeatherNotificationService
  extends IntentService {

  public static final String WEATHER_DATA = "feuerwehr.WeatherData";

  private static final String NAME = "WeatherNotificationService";

  public WeatherNotificationService() {
    super(NAME);
  }

  @Override
  protected void onHandleIntent(Intent newIntent) {

    Log.d(NAME, "handle");

    Context context = getApplicationContext();

    try {
      String json = WeatherWsFacade.getWeather(context);
      String lastReceive = FileUtil.readFile(context, WEATHER_DATA);

      if (json != null && !json.equals(lastReceive)) {

        FileUtil.writeFile(context, WEATHER_DATA, json);
        Log.i(NAME, "new Data: " + json);

        Notify.getInstance().add(context, getString(R.string.lblWeatherNotificationTickerText));
      }

    } catch (Exception ex) {
      Log.e(NAME, ex.getMessage(), ex);
    }
  }
}
